package com.guqj.mq.activitemq.destination.composite;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;

import com.guqj.mq.activitemq.ActiveMQFactory;

/**
 * 消息生产者-Composite Destinations
 * 
 * @author guqj
 * 
 */
public class JmsProducer extends ActiveMQFactory {

	/**
	 * 客户端模式
	 */
	public static void clientModel(){
		String queue = "composite-queue1,composite-queue2";
		Session session = null;
		Connection connection = null;
		try {
			connection = createConnection();
			// 创建session
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			MessageProducer producer = createProducer(session, queue);
			for (int i = 0; i < 10; i++) {
				sendMessage(session, producer, "Cient Model: ActiveMQ 发送的消息：" + (i + 1));
			}
			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			closeSource(connection, session);
		}
	}
	
	/**
	 * xml模式
	 * 组合队列允许用一个虚拟的destination代表多个destinations。这样就可以通过composite destinations在一个操作中同时向多个queue发送消息
	 */
	public static void xmlModel(){
		String queue = "COMPOSITE.QUEUE";
		Session session = null;
		Connection connection = null;
		try {
			connection = createConnection();
			// 创建session
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			MessageProducer producer = createProducer(session, queue);
			for (int i = 0; i < 10; i++) {
				sendMessage(session, producer, "XML Model: ActiveMQ 发送的消息：" + (i + 1));
			}
			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			closeSource(connection, session);
		}
	}
	
	/**
	 * 虚拟Topic
	 * 默认情况下，ActiveMQ开启了VirtualTopic特性，此时Topic的默认命名空间为“VirtualTopic.>”，
	 * 即命名模式为“VirtualTopic.<topicName>”，比如“VirtualTopic.order”；
	 * 那么对于consumer而言，对应的Queue命名模式为“Consumer.*.VirtualTopic.<topicName>”，
	 * 其中“*”的语义类似于clientId。
	 * @throws JMSException
	 */
	public static void virtualTopic() throws JMSException {
		Connection connection =  createConnection();
		// 创建session
		Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
		Destination destination = session.createTopic("VirtualTopic.Orders");
		MessageProducer producer = session.createProducer(destination);
		producer.setDeliveryMode(DeliveryMode.PERSISTENT); // 设置DeliveryMode.PERSISTENT模式
		for (int i = 0; i < 200; i++) {
			sendMessage(session, producer, "Virtual Topic: ActiveMQ 发送的消息：" + (i + 1));
		}
		session.commit();
	}
	
	public static void main(String[] args) throws JMSException {
		virtualTopic();
	}
	
}
